package com.gmq.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gmq.common.R;
import com.gmq.entity.Category;
import com.gmq.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;


    @PostMapping
    public R<String> save(@RequestBody Category category) {
        log.info("添加分类{}", category);
        categoryService.save(category);
        return R.success("新增分类成功");
    }

    @GetMapping("/page")
    public R<Page<Category>> page(int page, int pageSize) {
        log.info("查询分类管理分页{},{}", page, pageSize);
        //构造分页器
        Page<Category> page1 = new Page(page, pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.orderByAsc(Category::getSort);
        categoryService.page(page1, queryWrapper);
        return R.success(page1);
    }

    @DeleteMapping
    public R<String> delete(Long ids) {
        log.info("删除分类{}", ids);
        categoryService.removeCategory(ids);
        categoryService.removeById(ids);
        return R.success("删除成功");
    }

    @PutMapping
    public R<String> edit(@RequestBody Category category) {
        log.info("修改分类{}", category);
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    @GetMapping("/list")
    public R<List<Category>> list(@RequestParam(required = false) Object type) {
        log.info("查询菜品列表");
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        if (type != null) {
            queryWrapper.like(Category::getType, type);
        }

        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }

}
